<template>
  <el-menu
      :default-active="activeIndex"
      class="el-menu-vertical"
      :collapse="props.isCollapse"
      :unique-opened="true"
      active-color="#409eff"
      background-color="#233357"
      text-color="#FFFFFF"
      @open="handleOpen"
      @close="handleClose"
      @select="handleSelect"
  >
    <div v-for="item in menuList">
      <el-menu-item :index="item.id" v-show="!item.children || !item.children.length">
        <img style="margin-right: 0.2rem;" :src="bingIcon(item.id)" alt="" srcset=""/>
        <span style="font-size:0.2rem">{{ item.text }}</span>
      </el-menu-item>
      <el-sub-menu :index="item.id" v-show="item.children && item.children.length">
        <template #title>
          <img style="margin-right: 0.2rem;" :src="bingIcon(item.id)" alt="" srcset=""/>
          <span style="font-size:0.2rem">{{ item.text }}</span>
        </template>
        <div v-for="third in item.children">
          <el-menu-item-group v-show="third.url">
            <el-menu-item :index="third.id">{{ third.text }}</el-menu-item>
          </el-menu-item-group>
          <el-sub-menu v-show="!third.url" :index="third.id">
            <template #title>
              <img style="margin-right: 0.2rem;" :src="bingIcon(item.id)" alt="" srcset=""/>
              <span style="font-size:0.2rem">{{ third.text }}</span>
            </template>
            <el-menu-item-group>
              <el-menu-item :index="fourth.id" v-for="fourth in third.children">{{
                  fourth.text
                }}
              </el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
        </div>

      </el-sub-menu>
    </div>
  </el-menu>
</template>

<script lang="ts" setup>
import {ref, toRefs} from 'vue'
import {useRouter} from 'vue-router'
import {userStoreWithOut} from '@/stores/modules/userStore'
import {makeTree} from '@/common/util'
import index_icon from "@/assets/images/menu/10163100.png"
import robot_icon from "@/assets/images/menu/10163101.png"
import plat_icon from "@/assets/images/menu/10163102.png"
import staff_icon from "@/assets/images/menu/10163103.png"
import scenes_icon from "@/assets/images/menu/10163104.png"
import design_icon from "@/assets/images/menu/10163110.png"
import monitor_icon from "@/assets/images/menu/10163105.png"
import review_icon from "@/assets/images/menu/1016306.png"

const router = useRouter()
// 从缓存中获取菜单数据，并转换为树结构
// const userStore = userStoreWithOut()
 const menus_ = JSON.parse(localStorage.getItem('menus'))
 console.log('menus_',menus_)
const menus = ref(menus_) // 是响应式
 console.log('menus_',menus.value)
const activeIndex = ref('')
const menuList = makeTree('id', 'parent', menus.value)
const modulesFiles = import.meta.globEager('../assets/images/menu/*.png');
let modules = [];
for (const path in modulesFiles) {
  modules = [].concat(modules, modulesFiles[path].default);
}
const props = defineProps(['isCollapse'])
/*菜单目录打开*/
const handleOpen = (key: string, keyPath: string[]) => {
  activeIndex.value = key
}

/*菜单目录关闭*/
const handleClose = (key: string, keyPath: string[]) => {
}


const iconListMapDev=new Map([
  ['10163100',index_icon],
  ['10163101',robot_icon],
  ['10163102',plat_icon],
  ['10163103',staff_icon],
  ['10163104',scenes_icon],
  ['10163110',design_icon],
  ['10163105',monitor_icon],
  ['1016306',review_icon]
]);

const iconListMapProd=new Map([
  ['1033100',index_icon],
  ['1033101',robot_icon],
  ['1033102',plat_icon],
  ['1033103',staff_icon],
  ['1033104',scenes_icon],
  ['10163110',design_icon],
  ['1033105',monitor_icon],
  ['1033106',review_icon]
]);

const bingIcon = (icon) => {

  if(import.meta.env.MODE=='prod'){
    console.log("prod")
    if(iconListMapProd.get(icon)){
      return iconListMapProd.get(icon);
    }else{
      return new URL(`../assets/images/menu/list.png`, import.meta.url).href;
    }
  }else{
    if(iconListMapDev.get(icon)){
      return iconListMapDev.get(icon);
    }else{
      return new URL(`../assets/images/menu/list.png`, import.meta.url).href;
    }
  }


  // if (modules.some((v) => v.indexOf(icon + '.png') !== -1)) {
  //   return new URL(`../assets/images/menu/${icon}.png`, import.meta.url).href;
  // }
  // return new URL(`../assets/images/menu/list.png`, import.meta.url).href;
}

/*叶子菜单点击事件*/
const handleSelect = (key: string, keyPath: string[]) => {
  activeIndex.value = key
  getTargetUrl(key, keyPath, JSON.parse(JSON.stringify(menus.value)))
}

/*根据keyPath , menuList选出数据*/
const getTargetUrl = (key: string, keyPath: String[], menuList: any[]) => {
  if (keyPath.length > 0) {
    if (keyPath.length === 1) {
      menuList.forEach((item: any) => {
        if (item.id === key) {
          linkTo(item.url)
          return false
        }
      })
    } else {
      let list: any[];
      menuList.forEach((item: any) => {
        if (item.id === keyPath[0]) {
          list = item.children
        }
      })
      getTargetUrl(key, keyPath.slice(1), list);
    }
  }
}

/*菜单跳转*/
const linkTo = (path: string) => {
  /**
   * sso链接处理
   */
  if (path.indexOf('sso://') !== -1) {
    const targetClientId = path.replace('sso://', '')
    console.log(targetClientId)
    store.dispatch('auth/singleSign', {targetClientId}).then(resp => {
      console.log(resp)
      const {code, targetUrl} = resp
      window.open(`${targetUrl}?code=${code}`)
    })
  } else if (path.indexOf('open://') !== -1) {
    var index = path.lastIndexOf('targetURL')
    var url = path.substring(index, path.length)
    url = url.replace('targetURL=', '')
    api.linkSso({empeeAcct: store.getters['auth/user'].loginAcct, targetURL: url}).then(res => {
      if (res.data.data) {
        window.open(res.data.data)
      }
    })
  } else {
    router.push(path)
  }
}
</script>

<style>
/* .el-menu-vertical {
  height: 100vh;
  overflow-y: auto;
} */
</style>
